﻿namespace BEGDC.CC.Web.UserControls.CR
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Collections;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.Common.Query;

    /// <summary>
    ///		Summary description for CheckApp.
    /// </summary>
    public class CheckApp : BaseCR
    {
        #region Variables
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected System.Web.UI.WebControls.Button Btn_Submit;
        protected System.Web.UI.WebControls.Button Btn_Query;
        protected System.Web.UI.WebControls.Button Btn_Reject;
        protected System.Web.UI.WebControls.Button Btn_Reply;
        protected System.Web.UI.WebControls.Button Btn_Save;
        protected BEGDC.CC.Web.UserControls.CR.NormalCtrl NormalCtrl;
        protected BEGDC.CC.Web.UserControls.CR.PrintCtrl PrintCtrl;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected BEGDC.CC.Web.UserControls.CR.EZCtrl EZCtrl;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected BEGDC.CC.Web.Common.StampCtrl StampCtrl1;
        bool isReadOnly = false;
        bool saveBeforeSubmit = false;//joan 2008/8/23
        #endregion

        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }
        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {
                //John Add 8/12
                InValidAllSession();

                base.PreInitForm();

                //this.Btn_Save.Attributes["onclick"] = "javascript:OnSave();";
                this.Btn_Submit.Attributes["onclick"] = "javascript:OnSubmit();";
                this.Btn_Query.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["AppID"] + ");");
                this.Btn_Reject.Attributes.Add("onclick", "javascript:OpenCommentPane();");
                this.Btn_Reply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["FlowID"] + ");");
                ButtonStatusSetting();

                InitForm();

            }
        }

        #region SetStamp
        //		private void SetStamp()
        //		{
        //			IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
        //			DataTable table = queryService.QueryActionLog( this.AppID );
        //			StampCtrl1.SetDataSource( table );
        //		}
        #endregion

        #region ControlStatusSetting
        private void ControlStatusSetting(Accessibility access)
        {
            if (access == Accessibility.Readonly)
            {
                this.DisableChildrenControls(this);
                //this.stampCtrl1.Visible = false;
            }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            long flowId = this.LoadApplication();

            if (this.Application.AppNo != string.Empty)
                this.lbAppNo.Text = " Application No:" + this.Application.AppNo;

            if (this.Application != null)
            {
                //decide the application type whether EZ or normal
                if (!this.Application.IsTransition)
                {
                    EZCtrl.Visible = false;
                    //PrintCtrl.Visible = false;
                    NormalCtrl.Visible = true;

                    NormalCtrl.isReadOnly = isReadOnly;
                    NormalCtrl.App = this.Application;


                    this.NormalCtrl.DisableCATBranchAcount();
                }
                else
                {
                    EZCtrl.Visible = true;
                    NormalCtrl.Visible = false;

                    EZCtrl.isReadOnly = isReadOnly;
                    //this.Btn_Export.Visible = true;
                    //EZCtrl.Application = this.Application;
                    //EZCtrl.LoadCtrl();

                    this.EZCtrl.DisableCATBranchAcount();
                }
            }
            else
            {
                WebUtility.Go2ErrorPage(this.Page, "wrong Application ID");
            }
        }
        #endregion

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Reply.Click += new EventHandler(Btn_Reply_Click);
            this.Btn_Query.Click += new EventHandler(Btn_Query_Click);
            this.Btn_Reject.Click += new EventHandler(Btn_Reject_Click);
            this.Btn_Save.Click += new EventHandler(Btn_Save_Click);
            this.Btn_Submit.Click += new EventHandler(Btn_Submit_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        #region BuildObjects

        private DataTable BuildSessionTable(string SessionName)
        {
            DataTable dataTable = null;
            object SessDataTable = Session[SessionName];
            if (SessDataTable != null)
            {
                dataTable = (DataTable)SessDataTable;
            }
            return dataTable;
        }

        private void InValidAllSession()
        {
            Session[SessionFlag.CustomerSession] = null;
            Session[SessionFlag.AccompanySession] = null;
            Session[SessionFlag.HotelSession] = null;
            Session[SessionFlag.CompanyCarSession] = null;
            Session[SessionFlag.LeaseCarSession] = null;
            Session[SessionFlag.AccompanySessionEZ] = null;
            Session[SessionFlag.CustomerSessionEZ] = null;
            Session[SessionFlag.CompanyCarSessionEZ] = null;
            Session[SessionFlag.LeaseCarSessionEZ] = null;
            Session[SessionFlag.HotelSessionEZ] = null;
            Session[SessionFlag.ContractInfo] = null;
            Session[SessionFlag.CostCenter] = null;
            Session["CATDirector"] = null;
            Session["CATVP"] = null;
            Session["PSOHead"] = null;
            Session["DeptDirector"] = null;
            Session["DeptHead"] = null;
            Session["FNCController"] = null;
        }

        #endregion

        #region Save
        void Btn_Save_Click(object sender, EventArgs e)
        {
            string url = string.Empty + Request.Form["tbURL"];
            string script = "<script>";
            try
            {
                ImplementSave();

                if (url == string.Empty)
                    script += "alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                if (url != string.Empty)
                {
                    script += "window.location.href='" + url + "'";
                }
                script += "</script>";


            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
            if (!this.saveBeforeSubmit)
            {
                Page.RegisterClientScriptBlock("", script);
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');</script>");
            }
        }

        private void ImplementSave()
        {

            try
            {
                //OBTAIN BASIC INFORMATION
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;

                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                if (!App.IsTransition)
                {
                    App = NormalCtrl.BuildApplication(App);
                    BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
                    BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
                    IList VisitingList = NormalCtrl.BuildAppVisiting();

                    //OBTAIN SESSION INFORMATION
                    DataTable CustomerTable = BuildSessionTable(SessionFlag.CustomerSession);
                    DataTable AccompanyTable = BuildSessionTable(SessionFlag.AccompanySession);
                    DataTable HotelTable = BuildSessionTable(SessionFlag.HotelSession);
                    DataTable CompanyCarTable = BuildSessionTable(SessionFlag.CompanyCarSession);
                    DataTable LeaseCarTable = BuildSessionTable(SessionFlag.LeaseCarSession);

                    string Dept_Value = NormalCtrl.Dp_Dept_Value;
                    string CAT_Value = NormalCtrl.Dp_CAT_Value;

                    CRService.SaveNormalCheckApplication(App, customerinfo, logisticinfo, VisitingList, CustomerTable, AccompanyTable, HotelTable, CompanyCarTable, LeaseCarTable);
                }
                else
                {
                    Application app = new Application();
                    if (this.Application != null)
                    {
                        app.Id = this.AppID;
                        app.AppNo = this.Application.AppNo;
                        app.IsTransition = this.Application.IsTransition;
                        app.DepartmentType = this.Application.DepartmentType;
                        app.DepartmentName = this.Application.DepartmentName;
                    }

                    CustomerInfo customer = new CustomerInfo();
                    BusinessPurpose business = new BusinessPurpose();
                    Topic topic = new Topic();
                    SalesTeamInfo salesTeam = new SalesTeamInfo();
                    LogisticalInfo logist = new LogisticalInfo();
                    PaymentInfo payment = new PaymentInfo();
                    IList customerAttendee = new ArrayList();
                    IList alAttendee = new ArrayList();
                    IList site = new ArrayList();
                    IList cost = new ArrayList();
                    IList contract = new ArrayList();
                    //update Jovi
                    DataTable HotelTable = null;
                    DataTable CompanyCarTable = null;
                    DataTable LeaseCarTable = null;

                    EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                    CRService.SaveEZVisitCheckApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, false, true);

                    this.AppID = app.Id;
                    this.Application = app;
                    EZCtrl.CustomerID = customer.Id;
                    //EZCtrl.TopicID = topic.Id;
                    EZCtrl.SalesTeamID = salesTeam.Id;
                    EZCtrl.LogistID = logist.Id;
                    EZCtrl.BusinessID = business.Id;
                    EZCtrl.PaymentID = payment.Id;
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
        #endregion

        #region Submit
        void Btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string msg;
                this.saveBeforeSubmit = true;
                this.Btn_Save_Click(this.Btn_Save, null);
                this.saveBeforeSubmit = false;
                msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID);

                if (msg != "" && msg != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }

                //OBTAIN BASIC INFORMATION
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;

                //DECISION QUERY/SUBMIT
                if (this.tbOperationFlag.Text == "reply")
                {
                    //CRService.SaveCheckApplication(App,customerinfo,logisticinfo,VisitingList, CustomerTable,AccompanyTable,HotelTable,CompanyCarTable,LeaseCarTable);
                    CRService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));
                }
                else
                {
                    BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                    if (!App.IsTransition)
                    {
                        App = NormalCtrl.BuildApplication(App);
                        BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
                        BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
                        IList VisitingList = NormalCtrl.BuildAppVisiting();

                        //OBTAIN SESSION INFORMATION
                        DataTable CustomerTable = this.NormalCtrl.CustomerDataTable;
                        DataTable AccompanyTable = this.NormalCtrl.ALAttendeeDataTable;
                        DataTable HotelTable = this.NormalCtrl.HotelDataTable;
                        DataTable CompanyCarTable = this.NormalCtrl.CompanyCarDataTable;
                        DataTable LeaseCarTable = this.NormalCtrl.LeaseCarDataTable;

                        CRService.SubmitNormalCheckApplication(App, customerinfo, logisticinfo, VisitingList, CustomerTable, AccompanyTable, HotelTable, CompanyCarTable, LeaseCarTable, this.tbComment.Text);
                    }
                    else
                    {
                        Application app = new Application();
                        if (this.Application != null)
                        {
                            app.Id = this.AppID;
                            app.AppNo = this.Application.AppNo;
                            app.IsTransition = this.Application.IsTransition;
                            app.DepartmentType = this.Application.DepartmentType;
                            app.DepartmentName = this.Application.DepartmentName;
                        }

                        CustomerInfo customer = new CustomerInfo();
                        BusinessPurpose business = new BusinessPurpose();
                        Topic topic = new Topic();
                        SalesTeamInfo salesTeam = new SalesTeamInfo();
                        LogisticalInfo logist = new LogisticalInfo();
                        PaymentInfo payment = new PaymentInfo();
                        IList customerAttendee = new ArrayList();
                        IList alAttendee = new ArrayList();
                        IList site = new ArrayList();
                        IList cost = new ArrayList();
                        IList contract = new ArrayList();
                        //update Jovi
                        DataTable HotelTable = null;
                        DataTable CompanyCarTable = null;
                        DataTable LeaseCarTable = null;

                        EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                        CRService.SubmitEZVisitCheckApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, true, this.tbComment.Text);
                    }
                }

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
                //InValidAllSession();
            }
            catch (Exception exp)
            {
                if (exp.InnerException != null)

                    Page.RegisterClientScriptBlock("", "<script>alert('" + exp.InnerException.Message + "');</script>");
                else
                    Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
                //InValidAllSession();
            }
        }
        #endregion

        #region Query
        void Btn_Query_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag.Text == "query")
                {
                    ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                    CRService.Query(Convert.ToInt64(Request.QueryString["FlowID"]), this.tbOperationContent.Text, Session["Comment"].ToString());

                    Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
                }
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Reject
        void Btn_Reject_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                CRService.RejectCheckApplication(Convert.ToInt64(Request.QueryString["FlowID"]), WorkTransition.Reject, this.tbComment.Text, true);

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Export
        private void Btn_Export_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ExcelTool.ICCExcelExport excelExport;
                if (this.Application.IsTransition)
                    excelExport = new ExcelTool.ExportCRFormA();
                else
                    excelExport = new ExcelTool.ExportCRFormB();
                excelExport.Export(this.Page, this.AppID);
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
            }
        }
        #endregion

        #region ButtonStatusSetting
        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.Btn_Save.Visible = this.Access.IsButtonVisible(CRTransitionList.Save);
            this.Btn_Query.Visible = this.Access.IsButtonVisible(CRTransitionList.Query);
            this.Btn_Submit.Visible = this.Access.IsButtonVisible(CRTransitionList.Check);
            this.Btn_Reject.Visible = this.Access.IsButtonVisible(CRTransitionList.Reject);
            this.Btn_Reply.Visible = this.Access.IsButtonVisible(CRTransitionList.Reply);

            if ((this.Access.IsReadOnly || this.IsView))
                isReadOnly = true;
        }
        #endregion

        #region Reply
        void Btn_Reply_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;

                ImplementSave();

                CRService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }
        #endregion
    }
}
